from fastapi import APIRouter, HTTPException, status, Query
from tortoise.exceptions import DoesNotExist
from models.cart import Cart
from schemas.cart_schemas import  CartItem , CartListResponse
from datetime import datetime
from typing import List, Dict, Any
from pydantic import ValidationError

router = APIRouter(prefix="/api")

# 购物车列表查询
@router.get("/cart/list", response_model=dict)
async def get_cart_list(user_id: int = Query(1, description="用户ID")):  
    try:
        cart_items = await Cart.filter(user_id=user_id).all()
        response_data = {
            "code": 200,
            "message": "success",
            "data": {
                "items": []
            }
        }
        if cart_items:
            response_data["data"]["items"] = [
                {
                    "id": item.id,
                    "product_id": item.product_id,
                    "image_url": item.image_url.strip(),
                    "product_name": item.product_name,
                    "price": float(item.price),
                    "quantity": item.quantity,
                    "specs": item.specs,
                    "toppings": item.toppings
                }
                for item in cart_items
            ]
        return response_data
    except Exception as e:
        return {
            "code": 500,
            "message": f"查询失败: {str(e)}",
            "data": {"items": []}  # 异常时也返回空数组
        }
    

# 加入购物车接口
@router.post(
    "/cart/add", 
    summary="添加商品到购物车",
    description="存在则更新数量，不存在则创建新记录",
    tags=["购物车"]
)
async def add_to_shopcar(item: CartItem):
    try:
        existing_item = await Cart.get_or_none(
            user_id=item.user_id,
            product_id=item.product_id,
            specs=item.specs,
            toppings=item.toppings
        )

        if existing_item:
            existing_item.quantity += item.quantity
            existing_item.update_time = datetime.now()
            await existing_item.save()
            return {
                "code": 200,
                "message": "已更新购物车数量",
                "data": {
                    "id": existing_item.id,
                    "quantity": existing_item.quantity  # 只返回关键更新信息
                }
            }
        else:
            new_item_data = item.dict()
            new_item_data.update({
                "add_time": datetime.now(),
                "update_time": datetime.now()
            })
            new_item = await Cart.create(** new_item_data)
            return {
                "code": 201,
                "message": "已添加到购物车",
                "data": {
                    "id": new_item.id,
                    "quantity": new_item.quantity
                }
            }

    except ValidationError as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail={
                "code": status.HTTP_422_UNPROCESSABLE_ENTITY,
                "message": f"请求数据校验失败: {str(e)}",
                "data": {}
            }
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"添加购物车失败: {str(e)}",
                "data": {}
            }
        )

# 更新商品数量接口（补充完整截断部分）
@router.patch(
    "/cart/item/{item_id}/quantity",
    summary="更新购物车商品数量",
    tags=["购物车"]
)
async def update_cart_item_quantity(
    item_id: int, 
    quantity: int = Query(..., ge=1, description="商品数量（至少1）")  # 用Query限制最小值
):
    try:
        item = await Cart.get(id=item_id)
        item.quantity = quantity
        item.update_time = datetime.now()
        await item.save()
        
        return {
            "code": 200,
            "message": "数量更新成功",
            "data": {
                "id": item.id,
                "quantity": item.quantity  # 返回更新后的数量
            }
        }
    except DoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail={
                "code": 404,
                "message": "商品不存在",
                "data": {}
            }
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "code": 500,
                "message": f"更新失败: {str(e)}",
                "data": {}
            }
        )

# 删除购物车商品接口（补充完整CRUD）
@router.delete(
    "/cart/item/{item_id}",
    summary="删除购物车商品",
    tags=["购物车"]
)
async def delete_cart_item(item_id: int):
    try:
        item = await Cart.get(id=item_id)
        await item.delete()
        return {
            "code": 200,
            "message": "删除成功",
            "data": {}
        }
    except DoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail={
                "code": 404,
                "message": "商品不存在",
                "data": {}
            }
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "code": 500,
                "message": f"删除失败: {str(e)}",
                "data": {}
            }
        )